# -*- coding: utf-8 -*-
"""
合并两个更新频繁的节点:
    Clash节点: https://github.com/shunfengziyuan/DY-Clash
    V2ray节点: https://github.com/freefq/free/blob/master/v2

@author: xiaoniu29
"""

from requests import get
from lxml import etree
from yaml import safe_load
from base64 import b64encode, b64decode
from urllib3 import disable_warnings
from sys import exc_info
#from traceback import print_tb
from urllib.parse import quote

disable_warnings()
github = 'https://github.com'
gitraw = 'https://raw.githubusercontent.com'
# v2ray节点
project = '/freefq/free'
headers = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
           "Accept-Encoding": "gzip, deflate, br",
           "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
           "Referer": github+project,
           "Upgrade-Insecure-Requests": '1',
           "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36",
           'Connection':'close'
    }
#print(configfile)
proxies = {
    "http": "socks5://127.0.0.1:1080", # V2rayN
    "https": "socks5://127.0.0.1:1080" # V2rayN
    }
#print('Proxy:', proxies['https'])
b64proxies = []
failFlag = ['s','s']
try:
    # v2ray节点更新地址固定,无需过多处理
    headers['Referer']=github+project+'/blob/master/v2'
    resp = get(gitraw+project+'/master/v2',headers=headers,verify=False,timeout=6,proxies=proxies)
    b64proxies = b64decode(resp.content).decode().split('\n')
except:
    print("freefq update failed!")
    failFlag[0] = 'f'
    pass
try:
    # Clash节点
    # 通过文件上传的方式更新,链接一直在变
    project = '/shunfengziyuan/DY-Clash'
    headers['Referer']=github+project
    resp = get(github+project+'/commits/main',headers=headers,verify=False,timeout=6,proxies=proxies)
    root = etree.HTML(resp.content)
    # 取最新的更新链接
    url = root.xpath('//a[@aria-label="Add files via upload"]/@href')[0]
    branch = url.split('/')[-1]
    headers['Referer']=github+url
    resp = get(github+url,headers=headers,verify=False,timeout=6,proxies=proxies)
    root = etree.HTML(resp.content)
    # 得到新的文件名,构造新更新链接
    filename = root.xpath('//a[contains(text(),"yml")]/text()')[0]
    #filepath = gitraw+project+'/main/'+filename
    headers['Referer']=github+project+f'/blob/{branch}/'+filename
    resp = get(gitraw+project+f'/{branch}/'+filename,headers=headers,verify=False,timeout=6,proxies=proxies)
    proxies = safe_load(resp.content)["proxies"]
    # 挤水
    for locp in proxies:
        locp['name']=locp['name'].replace('欢迎订阅Youtube顺丰','DY-Clash')
        if locp["type"]=='ss':
            b64s = b64encode(bytes(f'{locp["cipher"]}:{locp["password"]}@{locp["server"]}:{locp["port"]}',encoding='utf-8'))
            b64proxies.append('ss://{}#{}'.format(b64s.decode('utf-8'),locp["name"].replace(' ','+')))
        if locp["type"]=='vmess':
            if 'tls' in locp and locp["tls"]:
                locp["tls"] = "tls"
            else:
                locp["tls"] = ""
            if 'network' in locp:
                if locp['network'] == 'tcp':
                    b64s = b64encode(bytes('{'+f'\r\n  "v": "2",\r\n  "ps": "{locp["name"]}",\r\n  "add": "{locp["server"]}",\r\n  "port": "{locp["port"]}",\r\n  "id": "{locp["uuid"]}",\r\n  "aid": "{locp["alterId"]}",\r\n  "net": "{locp["network"]}",\r\n  "type": "none",\r\n  "path": "",\r\n  "host": "{locp["server"]}",\r\n  "tls": ""\r\n'+'}',encoding='utf-8'))
                else:
                    b64s = b64encode(bytes('{'+f'\r\n  "v": "2",\r\n  "ps": "{locp["name"]}",\r\n  "add": "{locp["server"]}",\r\n  "port": "{locp["port"]}",\r\n  "id": "{locp["uuid"]}",\r\n  "aid": "{locp["alterId"]}",\r\n  "net": "{locp["network"]}",\r\n  "type": "none",\r\n  "host": "{locp["ws-headers"]["Host"]}",\r\n  "path": "{locp["ws-path"]}",\r\n  "tls": "{locp["tls"]}"\r\n'+'}',encoding='utf-8'))
            else:
                b64s = b64encode(bytes('{'+f'\r\n  "v": "2",\r\n  "ps": "{locp["name"]}",\r\n  "add": "{locp["server"]}",\r\n  "port": "{locp["port"]}",\r\n  "id": "{locp["uuid"]}",\r\n  "aid": "{locp["alterId"]}",\r\n  "net": "",\r\n  "type": "none",\r\n  "host": "{locp["server"]}",\r\n  "path": "",\r\n  "tls": "{locp["tls"]}"\r\n'+'}',encoding='utf-8'))
            b64proxies.append('vmess://'+b64s.decode('utf-8'))
        if locp["type"]=='trojan':
            b64proxies.append(f'trojan://{locp["password"]}@{locp["server"]}:{locp["port"]}#{quote(locp["name"])}')
except:
    print("Unexpected error:", exc_info()[0:2])
    #print_tb(exc_info()[-1])
    print("DY-Clash update failed!")
    failFlag[1] = 'f'
    pass

# 保存文件
with open("b64mess.txt","w",encoding='utf-8') as f:
    f.write(b64encode(bytes('\n'.join(b64proxies),encoding='utf-8')).decode())

print(''.join(failFlag))